<?php

namespace Modules\User\Entities;

use Illuminate\Database\Eloquent\Builder;
use Modules\Order\Entities\BaseOrder;
use Modules\User\Entities\VipSku;
use ThrowException;

class VipOrder extends BaseOrder
{
    // VIP订单

    protected $guarded = [];
    protected $table = 'orders';
    public $isAutoComplete = true;  // 付款后自动完成订单

    static public $resourceName = 'VIP订单';

    static public $orderType = 'vip';

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('vipOrder', function(Builder $builder) {
            $builder->type('vip');
        });
    }

    // 生成订单编号
    public function generateNumber()
    {
        $number = 'V' . date('mdH') . $this->user_id . rand(10, 99);
        return $number;
    }

    // 支付完成后同步操作
    public function paidListenerSync()
    {
        $skuId = @$this->options['sku_id'];

        if ($skuId) {
            $vipSku = VipSku::getEntity([
                'id' => $skuId
            ]);

            $user = $this->user;

            list($startAt, $endAt, $purchaseType) = $vipSku->sendTo($user);

            $options = $this->options;
            $options['vip_start_at'] = $startAt;
            $options['vip_end_at'] = $endAt;
            $options['purchase_type'] = $purchaseType;
            $this->update([
                'options' => $options
            ]);
            
            \Log::error('VIP开通成功');

            // 此处应触发开通VIP事件
            // 后续优化，当前先用以下代码处理
            $user->checkAgentLevelUpdate();
            
        }
        else {
            \Log::error('开通失败，无效的VIP SKU ID');
        }

        return true;
    }

}
